<template>
  <div class="newsPublish">
    <Row>
      <Col span="18">
      <Card>
        <div class="margin-top-20 newsEditor">
          <Editor v-model="content"
                  id="tinymce"
                  :init="setting"
                  @onInit="editorInit"></Editor>
          <Spin fix
                v-if="spinShow">
            <Icon type="load-c"
                  size=18
                  class="demo-spin-icon-load"></Icon>
            <div>加载组件中...</div>
          </Spin>
        </div>
      </Card>
      </Col>
      <Col span="6"
           class="padding-left-10">
      <Card>
        <p slot="title">
          <Icon type="paper-airplane"></Icon>
          发布
        </p>
        <p class="margin-top-10">
          <Icon type="eye"></Icon>
          &nbsp;&nbsp;新闻标题：
        </p>
        <p class="margin-top-10">
          <Form :label-width="80">
            <Input v-model="articleTitle"
                   @on-blur="handleArticletitleBlur"
                   icon="android-list" />
          </Form>
        </p>
        <p class="margin-top-10">
          <Icon type="eye"></Icon>
          &nbsp;&nbsp;新闻作者：
        </p>
        <p class="margin-top-10">
          <Form :label-width="80">
            <Input v-model="newsAutor"
                   @on-blur="handleNewsAutorBlur"
                   icon="android-list" />
          </Form>
        </p>
        <p class="margin-top-10">
          <Icon type="eye"></Icon>
          &nbsp;&nbsp;新闻分类：
        </p>
        <p class="margin-top-10">
          <RadioGroup v-model="newsType"
                      @on-change="handleNewsType">
            <Radio label="0">行业新闻</Radio>
            <Radio label="1">公司新闻</Radio>
          </RadioGroup>
        </p>
        <p class="margin-top-10">
          <Icon type="ios-calendar-outline"></Icon>
          &nbsp;&nbsp;发布时间：
        </p>
        <p class="margin-top-10">
          <DatePicker type="date"
                      placeholder="Select date"
                      v-model="newsDate"
                      style="width: 100%"></DatePicker>
        </p>
        <Row class="margin-top-20 publish-button-con">
          <span class="publish-button ">
            <Button @click="handlePreview">预览</Button>
          </span>
        </Row>
        <p class="margin-top-10">
          <span class="publish-button">
            <Button @click="handlePublish"
                    :loading="publishLoading"
                    icon="ios-checkmark"
                    style="width:90px;"
                    type="primary">发布</Button>
          </span>
        </p>
      </Card>
      </Col>
    </Row>
  </div>
</template>

<script>
import server from "@/api/news.js";

import Editor from "@tinymce/tinymce-vue";
// 买不起apikey
import tinymce from "tinymce/tinymce";
import "tinymce/themes/modern/theme";
import "tinymce/plugins/advlist";
import "tinymce/plugins/lists";
import "tinymce/plugins/link";
import "tinymce/plugins/image";
import "tinymce/plugins/charmap";
import "tinymce/plugins/hr";
import "tinymce/plugins/anchor";
import "tinymce/plugins/pagebreak";
import "tinymce/plugins/imagetools";
import "tinymce/plugins/searchreplace";
import "tinymce/plugins/visualblocks";
import "tinymce/plugins/visualchars";
import "tinymce/plugins/code";
import "tinymce/plugins/fullpage";
import "tinymce/plugins/insertdatetime";
import "tinymce/plugins/media";
import "tinymce/plugins/nonbreaking";
import "tinymce/plugins/save";
import "tinymce/plugins/table";
import "tinymce/plugins/contextmenu";
import "tinymce/plugins/directionality";
import "tinymce/plugins/emoticons";
import "tinymce/plugins/paste";
import "tinymce/plugins/textcolor";
import "tinymce/plugins/colorpicker";
import "tinymce/plugins/textpattern";
import "tinymce/plugins/codesample";

export default {
  props: {
    url: {
      default: "",
      type: String
    },
    accept: {
      default: "image/jpeg, image/png",
      type: String
    },
    maxSize: {
      default: 2097152,
      type: Number
    },
    withCredentials: {
      default: false,
      type: Boolean
    }
  },
  data () {
    let self = this;
    return {
      articleTitle: localStorage.articleTitle,
      newsAutor: localStorage.newsAutor,
      newsType: localStorage.newsType,
      newsLabel: localStorage.newsLabel,
      newsDate: localStorage.newsDate,
      fixedLink: localStorage.fixedLink,
      content: "我是富文本编辑器的内容",
      publishLoading: false,
      setting: {
        branding: false,
        elementpath: false,
        height: 600,
        language_url: "/static/langs/zh_CN.js",
        language: "zh_CN",
        menubar: "edit insert view format table tools",
        external_plugins: {
          'emoticons': '/static/emoticons/plugin.min.js',
          'codesample': '/static/codesample/plugin.min.js'
        },
        skin_url: '/skins/lightgray',
        plugins: [
          "advlist lists link image charmap hr anchor pagebreak imagetools",
          "searchreplace visualblocks visualchars code fullpage",
          "insertdatetime media nonbreaking save table contextmenu directionality",
          "emoticons paste textcolor colorpicker textpattern codesample"
        ],
        toolbar: [
          " newnote | undo redo | insert | styleselect | fontselect | formatselect | fontsizeselect | forecolor backcolor bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent",
          " link image | codesample emoticons ",
        ],
        autosave_interval: "20s",
        forced_root_block: "p",
        force_p_newlines: true,
        importcss_append: true,
        // content默认样式
        content_style: `
          *                         { padding:0; margin:0; }
          html, body                { height:100%; }
          img                       { max-width:100%; display:block;height:auto; }
          a                         { text-decoration: none; }
          iframe                    { width: 100%; }
          p                         { line-height:1.6; margin: 0px; }
          table                     { word-wrap:break-word; word-break:break-all; max-width:100%; border:none; border-color:#999; }
          .mce-object-iframe        { width:100%; box-sizing:border-box; margin:0; padding:0; }
          ul,ol                     { list-style-position:inside; }
        `,
        insert_button_items: "image link | inserttable",
        paste_retain_style_properties: "all",
        paste_word_valid_elements: "*[*]", // word需要它
        paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传
        paste_convert_word_fake_lists: false, // 插入word文档需要该属性
        paste_webkit_styles: "all",
        paste_merge_formats: true,
        nonbreaking_force_tab: false,
        paste_auto_cleanup_on_paste: false,
        // 可选择的字体大小
        fontsize_formats: "10px 11px 12px 14px 16px 18px 20px 24px",
        // 可选择的段落样式
        style_formats: [
          {
            title: "首行缩进",
            block: "p",
            styles: { "text-indent": "2em" }
          },
          {
            title: "行高",
            items: [
              { title: "1", styles: { "line-height": "1" }, inline: "span" },
              {
                title: "1.5",
                styles: { "line-height": "1.5" },
                inline: "span"
              },
              { title: "2", styles: { "line-height": "2" }, inline: "span" },
              {
                title: "2.5",
                styles: { "line-height": "2.5" },
                inline: "span"
              },
              { title: "3", styles: { "line-height": "3" }, inline: "span" }
            ]
          }
        ],
        font_formats: `
          微软雅黑=微软雅黑;
          宋体=宋体;
          黑体=黑体;
          仿宋=仿宋;
          楷体=楷体;
          隶书=隶书;
          幼圆=幼圆;
          Andale Mono=andale mono,times;
          Arial=arial, helvetica,
          sans-serif;
          Arial Black=arial black, avant garde;
          Book Antiqua=book antiqua,palatino;
          Comic Sans MS=comic sans ms,sans-serif;
          Courier New=courier new,courier;
          Georgia=georgia,palatino;
          Helvetica=helvetica;
          Impact=impact,chicago;
          Symbol=symbol;
          Tahoma=tahoma,arial,helvetica,sans-serif;
          Terminal=terminal,monaco;
          Times New Roman=times new roman,times;
          Trebuchet MS=trebuchet ms,geneva;
          Verdana=verdana,geneva;
          Webdings=webdings;
          Wingdings=wingdings,zapf dingbats`,
        // Tab
        tabfocus_elements: ":prev,:next",
        object_resizing: true,
        // Image
        imagetools_toolbar:
          "rotateleft rotateright | flipv fliph | editimage imageoptions",
        images_upload_handler: function (blobInfo, success, failure) {
          if (blobInfo.blob().size > self.maxSize) {
            failure("文件体积过大");
          }
          if (self.accept.indexOf(blobInfo.blob().type) >= 0) {
            uploadPic();
          } else {
            failure("图片格式错误");
          }
          async function uploadPic () {
            let formData = new FormData();
            // 服务端接收文件的参数名，文件数据，文件名
            formData.append("upfile", blobInfo.blob(), blobInfo.filename());
            let res = await server.uploadImg(formData);
            if (res.code === 0) {
              success(res.data.url);
            } else if (res.code === 0) {
              failure("上传失败");
            }
          }
        }
      },
      spinShow: true
    };
  },
  watch: {
    content: {
      deep: true,
      handler (newVal) {
        localStorage.editorContent = newVal;
      }
    }
  },
  components: {
    Editor
  },
  methods: {
    handleNewsType (type) {
      localStorage.newsType = type;
      if (type === 1) {
        localStorage.newsLabel = "公司新闻";
      } else if (type === 0) {
        localStorage.newsLabel = "行业新闻";
      }
    },
    editorInit () {
      this.spinShow = false;
      if (localStorage.editorContent) {
        this.content = localStorage.editorContent;
      }
    },
    handleArticletitleBlur () {
      if (this.articleTitle.length !== 0) {
        localStorage.articleTitle = this.articleTitle;
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        this.fixedLink =
          window.location.host + "/" + year + "/" + month + "/" + day + "/";
      } else {
        this.$Message.error("文章标题不可为空哦");
      }
    },
    handleNewsAutorBlur () {
      localStorage.newsAutor = this.newsAutor;
    },
    canPublish () {
      if (this.articleTitle.length === 0) {
        this.$Message.error("请输入文章标题");
        return false;
      } else if (!this.newsType) {
        this.$Message.error("请选择新闻类型");
        return false;
      } else {
        return true;
      }
    },
    handlePreview () {
      if (this.canPublish) {
        if (!this.newsDate) {
          let date = new Date();
          let year = date.getFullYear();
          let month = date.getMonth() + 1;
          let day = date.getDate();
          let hour = date.getHours();
          let minute = date.getMinutes();
          let second = date.getSeconds();
          localStorage.publishTime =
            year +
            " 年 " +
            month +
            " 月 " +
            day +
            " 日 -- " +
            hour +
            " : " +
            minute +
            " : " +
            second;
        } else {
          localStorage.publishTime = this.newsDate;
        }
        this.$router.push({ name: "Preview" });
      }
    },

    async handlePublish () {
      if (this.canPublish()) {
        this.publishLoading = true;
        const news = {
          articleTitle: localStorage.articleTitle,
          editorContent: localStorage.editorContent,
          newsAutor: localStorage.newsAutor,
          newsType: parseInt(localStorage.newsType),
          newsLabel: localStorage.newsLabel,
          publishTime: localStorage.publishTime
        };

        let res;
        // 判断是编辑还是删除
        if (this.$route.query.handle === 'edit') {
          news._id = localStorage._id;
          res = await server.update(news);
        } else {
          res = await server.create(news);
        }

        //console.log(res);
        if (res.code === 0) {
          this.publishLoading = false;
          this.$Notice.success({
            title: "发布成功",
            desc: "文章《" + this.articleTitle + "》保存成功"
          });
        } else if (res.code === 1) {
          this.$Notice.error({
            title: "发布失败",
            desc: "文章《" + this.articleTitle + "》发布失败"
          });
        }
      }
    }
  },
  mounted () {
    tinymce.init({});
  }
};
</script>

<style lang="less">
@import "../../style/loading.less";
@import "./news-publish.less";
</style>